﻿using IniReadWrite;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using VisionRoc.Core;

namespace MultiLanguageDeluxeXML
{
    public class MultiLanguage
    {
        //当前默认语言
        public static string DefaultLanguage = "Chinese";

        //当前程序认为合法的所有语言
        private List<string> LanguageList = new List<string> { "Chinese", "English", "Vietnamese" };

        public List<Control> LControls = new List<Control>();


        ///// <summary>
        ///// 遍历窗体所有控件
        ///// </summary>
        ///// <param name="fatherControl"></param>
        //public void GetControls(Control fatherControl)
        //{
        //    Control.ControlCollection sonControls = fatherControl.Controls;
        //    //遍历所有控件
        //    foreach (Control control in sonControls)
        //    {
        //        LControls.Add(control);
        //        if (control.Controls != null)
        //        {
        //            GetControls(control);
        //        }
        //    }
        //}

        /// <summary>
        /// 可以获取窗体所有控件 
        /// </summary>
        /// <param name="parent"></param>
        public void GetControls(Control parent)
        {
            // 获取所有非公共字段（包括私有字段和受保护字段）
            var fields = parent.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (var field in fields)
            {
                // 确保字段是 Control 类型
                if (typeof(Control).IsAssignableFrom(field.FieldType))
                {
                    var control = field.GetValue(parent) as Control;
                    if (control != null)
                    {
                        LControls.Add(control);
                        // 如果控件还有子控件，则递归调用
                        GetControls(control);
                    }
                }
            }

            // 确保遍历所有子控件
            foreach (Control control in parent.Controls)
            {
                LControls.Add(control);
                // 递归调用遍历子控件
                GetControls(control);
            }
        }

        /// <summary>
        /// 窗体个别控件获取不到
        /// </summary>
        /// <param name="fatherControl"></param>
        public void GetControls2(Control fatherControl)
        {
            Control.ControlCollection sonControls = fatherControl.Controls;
            //遍历所有控件
            foreach (Control control in sonControls)
            {

                LControls.Add(control);
                if (control.Controls != null)
                {
                    GetControls2(control);
                }
            }
        }


        /// <summary>
        /// 从配置文件App.config中读取当前默认语言
        /// </summary>
        /// <returns>当前默认语言</returns>
        public string GetDefaultLanguage()
        {
            try
            {
                string defaultLanguage = "Chinese";
                bool flag = false;
                //判断配置文件中是否有存在DefaultLanguage项，不存在则添加
                foreach (string key in ConfigurationManager.AppSettings)
                {
                    if (key == "DefaultLanguage")
                    {
                        //存在
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    //读取默认语言
                    string result = ConfigurationManager.AppSettings["DefaultLanguage"].ToString();
                    //判断默认语言是否合法，不合法则将默认语言修改为ChineseSimplified
                    if (LanguageList.Contains(result))
                    {
                        defaultLanguage = result;
                    }
                    else
                    {
                        //修改配置文件的项
                        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        config.AppSettings.Settings["DefaultLanguage"].Value = "Chinese";
                        config.Save(ConfigurationSaveMode.Modified);
                        ConfigurationManager.RefreshSection("appSettings");
                    }
                }
                else
                {
                    //添加配置文件的项
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    config.AppSettings.Settings.Add("DefaultLanguage", "Chinese");
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");
                }
                return defaultLanguage;
            }
            catch
            {
                return "Chinese";
            }
        }
        string path = Application.StartupPath + "\\Solution" + "\\Language\\MyLanguage.ini";

        string defaultLanguage = "Chinese";
        /// <summary>
        /// 获取语言信息
        /// </summary>
        /// <returns></returns>
        public string GetDefaultLanguage2()
        {
            string result = IniAPI.INIGetStringValue(path, "Language", "Default", "0");
            if (LanguageList.Contains(result))
            {
                defaultLanguage = result;
            }

            return defaultLanguage;
        }

        public bool SetDefaultLanguage2(string lang, out string result)
        {
            if (LanguageList.Contains(lang))
            {
                IniAPI.INIWriteValue(path, "Language", "Default", lang);
                result = "修改默认语言成功";
                return true;
            }
            else
            {
                result = "非法语言，无法修改";
                return false;
            }
        }


        /// <summary>
        /// 修改配置文件App.config中的默认语言
        /// </summary>
        /// <param name="lang"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public bool SetDefaultLanguage(string lang, out string result)
        {
            SetDefaultLanguage2(lang, out string result2);
            //判断当前设置的语言是否合法
            if (LanguageList.Contains(lang))
            {
                try
                {
                    bool flag = false;
                    //判断配置文件中是否有存在DefaultLanguage项，不存在则添加，存在则修改为当前设置的语言
                    foreach (string key in ConfigurationManager.AppSettings)
                    {
                        if (key == "DefaultLanguage")
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (flag)
                    {
                        //修改配置文件的项
                        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        config.AppSettings.Settings["DefaultLanguage"].Value = lang;
                        config.Save(ConfigurationSaveMode.Modified);
                        ConfigurationManager.RefreshSection("appSettings");
                    }
                    else
                    {
                        //添加配置文件的项
                        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        config.AppSettings.Settings.Add("DefaultLanguage", lang);
                        config.Save(ConfigurationSaveMode.Modified);
                        ConfigurationManager.RefreshSection("appSettings");
                    }
                    //修改默认语言
                    DefaultLanguage = lang;
                    result = "修改默认语言成功";
                    return true;
                }
                catch (Exception ex)
                {
                    result = "修改默认语言失败： " + ex.Message;
                    return false;
                }
            }
            else
            {
                result = "非法语言，无法修改";
                return false;
            }
        }




        /// <summary>
        /// 加载程序语言
        /// 在窗口的Load函数中进行默认语言加载
        /// </summary>
        /// <param name="form">加载语言的窗口</param>
        /// <param name="result">加载结果</param>
        /// <returns></returns>
        public bool LoadLanguage(Form form, out string result)
        {
            //获取当前默认语言   原
            //string language = GetDefaultLanguage();
            //获取当前默认语言   新
            string language = GetDefaultLanguage2();
            //根据用户选择的语言获得表的显示文字 
            Hashtable hashText = ReadXMLText(form.Name, language);
            Hashtable hashHeaderText = ReadXMLHeaderText(form.Name, language);
            if (hashText == null || hashHeaderText == null)
            {
                //防止下载启动程序，再次加载错误语言   新
                SetDefaultLanguage2("Chinese", out result);
                ////防止下载启动程序，再次加载错误语言 原
                //SetDefaultLanguage("Chinese", out result);
                result = "加载语言包失败，可能原因：语言包损坏";
                return false;
            }
            //获取当前窗口的所有控件
            //Control.ControlCollection sonControls = form.Controls;
            int num = LControls.Count;
            try
            {
                //遍历所有控件
                foreach (Control control in LControls)
                {
                    if (control.GetType() == typeof(Panel))     //Panel
                    {
                        GetSetSubControls(control.Controls, hashText, hashHeaderText);
                    }
                    else if (control.GetType() == typeof(GroupBox))     //GroupBox
                    {
                        GetSetSubControls(control.Controls, hashText, hashHeaderText);
                    }
                    else if (control.GetType() == typeof(TabControl))       //TabControl
                    {
                        GetSetSubControls(control.Controls, hashText, hashHeaderText);
                    }
                    else if (control.GetType() == typeof(TabPage))      //TabPage
                    {
                        GetSetSubControls(control.Controls, hashText, hashHeaderText);
                    }
                    else if (control.GetType() == typeof(MenuStrip))      //MenuStrip
                    {
                        GetSetMenuStrip((MenuStrip)control, hashText);
                    }
                    else if (control.GetType() == typeof(StatusStrip))      //StatusStrip  ToolStripDropDownMenu
                    {
                        GetSetStatusStrip((StatusStrip)control, hashText);
                    }
                    else if (control.GetType() == typeof(ContextMenuStrip))      // ContextMenuStrip
                    {
                        GetSetContextMenuStrip((ContextMenuStrip)control, hashText);
                    }
                    else if (control.GetType() == typeof(DataGridView))
                    {
                        GetSetHeaderCell((DataGridView)control, hashHeaderText);
                    }
                    if (hashText.Contains(control.Name.ToLower()))
                    {
                        control.Text = (string)hashText[control.Name.ToLower()];
                    }
                }
                if (hashText.Contains(form.Name.ToLower()))
                {
                    form.Text = (string)hashText[form.Name.ToLower()];
                }
                result = "";
                return true;
            }
            catch (Exception ex)
            {
                //防止下载启动程序，再次加载错误语言
                SetDefaultLanguage2("Chinese", out result);
                ////防止下载启动程序，再次加载错误语言
                //SetDefaultLanguage("Chinese", out result);
                result = "加载语言包失败： " + ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 获取并设置控件中的子控件
        /// </summary>
        /// <param name="controls">父控件</param>
        /// <param name="hashResult">哈希表</param>
        private void GetSetSubControls(Control.ControlCollection controls, Hashtable hashText, Hashtable hashHeaderText)
        {
            try
            {
                foreach (Control control in controls)
                {
                    if (control.GetType() == typeof(Panel))     //Panel
                    {
                        GetSetSubControls(control.Controls, hashText, hashHeaderText);
                    }
                    else if (control.GetType() == typeof(GroupBox))     //GroupBox
                    {
                        GetSetSubControls(control.Controls, hashText, hashHeaderText);
                    }
                    else if (control.GetType() == typeof(TabControl))       //TabControl
                    {
                        GetSetSubControls(control.Controls, hashText, hashHeaderText);
                    }
                    else if (control.GetType() == typeof(TabPage))      //TabPage
                    {
                        GetSetSubControls(control.Controls, hashText, hashHeaderText);
                    }
                    else if (control.GetType() == typeof(MenuStrip))      //MenuStrip
                    {
                        GetSetMenuStrip((MenuStrip)control, hashText);
                    }
                    else if (control.GetType() == typeof(StatusStrip))      //StatusStrip
                    {
                        GetSetStatusStrip((StatusStrip)control, hashText);
                    }
                    else if (control.GetType() == typeof(DataGridView))
                    {
                        GetSetHeaderCell((DataGridView)control, hashHeaderText);
                    }
                    if (hashText.Contains(control.Name.ToLower()))
                    {
                        control.Text = (string)hashText[control.Name.ToLower()];
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 获取并设置DataGridView的列头
        /// </summary>
        /// <param name="dataGridView">DataGridView名</param>
        /// <param name="hashResult">哈希表</param>
        private void GetSetHeaderCell(DataGridView dataGridView, Hashtable hashHeaderText)
        {
            foreach (DataGridViewColumn column in dataGridView.Columns)
            {

                if (hashHeaderText.Contains(column.Name.ToLower()))
                {
                    column.HeaderText = (string)hashHeaderText[column.Name.ToLower()];
                }
            }
        }

        /// <summary>
        /// 获取并设置GetSetMenuStrip
        /// </summary>
        private void GetSetMenuStrip(MenuStrip menuStrip, Hashtable hashHeaderText)
        {
            foreach (ToolStripMenuItem column in menuStrip.Items)
            {
                if (hashHeaderText.Contains(column.Name.ToLower()))
                {
                    column.Text = (string)hashHeaderText[column.Name.ToLower()];
                }

                if (column.DropDownItems.Count > 0)
                {
                    foreach (ToolStripMenuItem item in column.DropDownItems)
                    {
                        if (hashHeaderText.Contains(item.Name.ToLower()))
                        {
                            item.Text = (string)hashHeaderText[item.Name.ToLower()];
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 获取并设置GetSetStatusStrip
        /// </summary>
        private void GetSetStatusStrip(StatusStrip statusStrip, Hashtable hashHeaderText)
        {
            foreach (ToolStripStatusLabel column in statusStrip.Items)
            {
                if (hashHeaderText.Contains(column.Name.ToLower()))
                {
                    column.Text = (string)hashHeaderText[column.Name.ToLower()];
                }
            }
        }

        private static void GetSetContextMenuStrip(ContextMenuStrip statusStrip, Hashtable hashHeaderText)
        {
            foreach (ToolStripMenuItem column in statusStrip.Items)
            {
                if (hashHeaderText.Contains(column.Name.ToLower()))
                {
                    column.Text = (string)hashHeaderText[column.Name.ToLower()];
                }
            }
        }

        /// <summary>
        /// 从XML文件中读取需要修改Text的內容
        /// </summary>
        /// <param name="frmName">窗口名，用于获取对应窗口的那部分内容</param>
        /// <param name="lang">目标语言</param>
        /// <returns></returns>
        private Hashtable ReadXMLText(string frmName, string lang)
        {
            try
            {
                Hashtable hashResult = new Hashtable();
                XmlReader reader = null;
                //判断是否存在该语言的配置文件
                if (!(new System.IO.FileInfo(Application.StartupPath + "\\Solution" + "\\Language\\" + lang + ".xml")).Exists)
                {
                    return null;
                }
                else
                {
                    reader = new XmlTextReader(Application.StartupPath + "\\Solution" + "\\Language\\" + lang + ".xml");//"Languages/" + lang + ".xml"
                }
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);
                XmlNode root = doc.DocumentElement;
                //获取XML文件中对应该窗口的内容
                XmlNodeList nodeList = root.SelectNodes("Form[Name='" + frmName + "']/Controls/Control");
                //int i = 0;
                foreach (XmlNode node in nodeList)
                {
                    try
                    {
                        //修改内容为控件的Text值
                        XmlNode node1 = node.SelectSingleNode("@name");
                        XmlNode node2 = node.SelectSingleNode("@text");
                        if (node1 != null)
                        {
                            hashResult.Add(node1.InnerText.ToLower(), node2.InnerText);
                        }
                        //i++;
                    }
                    catch (Exception ex)
                    {
                        Global.AddLogInfoEvent(LogLevel.Warn, ex.ToString());
                    }
                }
                reader.Close();
                reader.Dispose();
                return hashResult;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 从XML文件中读取需要修改HeaderText的內容
        /// </summary>
        /// <param name="frmName">窗口名，用于获取对应窗口的那部分内容</param>
        /// <param name="lang">目标语言</param>
        /// <returns></returns>
        private Hashtable ReadXMLHeaderText(string frmName, string lang)
        {
            try
            {
                Hashtable hashResult = new Hashtable();
                XmlReader reader = null;
                //判断是否存在该语言的配置文件
                if (!(new System.IO.FileInfo(Application.StartupPath + "\\Solution" + "\\Language\\" + lang + ".xml")).Exists)//Application.StartupPath + "//" + lang + ".xml"
                {
                    return null;
                }
                else
                {
                    reader = new XmlTextReader(Application.StartupPath + "\\Solution" + "\\Language\\" + lang + ".xml");//"Languages/" + lang + ".xml"
                }
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);
                XmlNode root = doc.DocumentElement;
                //获取XML文件中对应该窗口的内容
                XmlNodeList nodeList = root.SelectNodes("Form[Name='" + frmName + "']/DataGridViewCells/DataGridViewCell");
                foreach (XmlNode node in nodeList)
                {
                    try
                    {
                        //修改内容为控件的Text值
                        XmlNode node1 = node.SelectSingleNode("@name");
                        XmlNode node2 = node.SelectSingleNode("@HeaderText");
                        if (node1 != null)
                        {
                            hashResult.Add(node1.InnerText.ToLower(), node2.InnerText);
                        }
                    }
                    catch { }
                }
                reader.Close();
                reader.Dispose();
                return hashResult;
            }
            catch
            {
                return null;
            }
        }
    }
}

